const express = require('express')
const users = require('../models/user')
const router = express.Router()
const jwt = require('jsonwebtoken')

// 获取所有用户列表
router.get('/userlist', (req, res) => {
  let token = req.get('Authorization')
  jwt.verify(token, 'abc', (err, decode) => {
    if (err) return res.send({code: 0, message: "token已失效"})
    const query = users.find()
    const page = req.query.pagenum
    const rows = 9
    query.skip((page - 1) * rows);
    query.limit(rows);
    query.exec((err, rs) => {
      if (err) {
        res.send(err);
      } else {
        //计算数据总数
        users.find((err, result) => {
          let obj = {}
          let userlist = []
          for (let i = 0; i < rs.length; i++) {
            obj[i] = {
              username: rs[i].username,
              gender: rs[i].gender,
              regDate: rs[i].regDate,
              auth: rs[i].auth,
              _id: rs[i]._id
            }
            userlist.push(obj[i])
          }
          res.send({
            message: '获取用户列表成功',
            total: result.length,
            data: userlist,
            status: 200
          })
        })
      }
    })
  })
})

// 添加用户
router.post('/user/new', (req, res) => {
  let token = req.get('Authorization')
  jwt.verify(token, 'abc', (err, decode) => {
    if (err) return res.send({code: 0, message: "token已失效"})
    users.findOne({
      username: req.body.username
    }, (err, data) => {
      if (err) return res.status(500).send({message: '添加用户失败', status: 500})
      if (data !== null) {
        return res.send({message: '用户名重复', status: 399})
      } else {
        new users(req.body).save((err => {
          if (err) return res.status(500).send({message: '添加用户失败', status: 500})
        }))
        res.send({
          message: '添加用户成功',
          status: 200
        })
      }
    })
  })
})

// 删除用户
router.delete('/user', (req, res) => {
  let token = req.get('Authorization')
  jwt.verify(token, 'abc', (err, decode) => {
    if (err) return res.send({code: 0, message: "token已失效"})
    users.findByIdAndRemove(req.query.id, req.body, err => {
      if (err) return res.status(500).send({ message: '删除用户失败', status: 500 })
      res.send({
        message: '删除用户成功',
        status: 200
      })
    })
  })
})

// 编辑用户
router.post('/user', (req, res) => {
  let token = req.get('Authorization')
  jwt.verify(token, 'abc', (err, decode) => {
    if (err) return res.send({code: 0, message: "token已失效"})
    users.findByIdAndUpdate(req.body._id, req.body, err => {
      if (err) return res.status(500).send({ message: '修改用户失败', status: 500 })
      res.send({
        message: '修改用户成功',
        status: 200
      })
    })
  })
})

module.exports = router
